package com.googlecode.monitoring.ws.service;

import com.googlecode.monitoring.dao.StatisticDao;
import com.googlecode.monitoring.model.ItemToCheck;
import com.googlecode.monitoring.model.StateName;
import com.googlecode.monitoring.service.MonitoringService;
import com.googlecode.monitoring.ws.model.ConfigBuilder;
import com.googlecode.monitoring.ws.model.TestFrameworkConfig;
import com.googlecode.monitoring.ws.model.WsItemToCheck;
import no.cicero.testframework.config.Config;
import no.cicero.testframework.execution.UseCasesRunnerWithOutReport;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Author: Sergiy Doroshenko
 * Date: Aug 31, 2010
 * Time: 4:11:04 PM
 */
@Service(value = "monitoringService")
public class WsMonitoringService implements MonitoringService {

    private StatisticDao statisticDao;
    private Logger log = Logger.getLogger(WsMonitoringService.class);

    @Autowired
    public void setStatisticDao(StatisticDao statisticDao) {
        this.statisticDao = statisticDao;
    }

    @Override
    public boolean checkIsItemOutdated(ItemToCheck item) {
        WsItemToCheck wsItemToCheck = (WsItemToCheck) item;
        boolean testfailed = false;
        try {
            runTestFramework(wsItemToCheck.getTestFrameworkConfig());
            wsItemToCheck.switchState(StateName.CHECKED);
            wsItemToCheck.setLastCheckTime(new DateTime());
            log.debug("The service is up");
            statisticDao.incrementTotalStateChecks(wsItemToCheck.getId());
        } catch (Exception e) {
            log.debug("The service is down");
            testfailed = true;
            statisticDao.incrementTotalStateDownChecks(wsItemToCheck.getId());
        }
        return testfailed;
    }

    public void runTestFramework(TestFrameworkConfig tfConfig) throws Exception {
        Config config = ConfigBuilder.build(tfConfig);
        new no.cicero.testframework.Starter() {
            public void start(Config config) throws Exception {
                new UseCasesRunnerWithOutReport(config).run();
            }
        }.start(config);
    }
}
